<template>
    <div>
        <!-- 分配权限窗口 -->
        <el-dialog title="编辑权限" v-model="state.editAuthorityDialogVisible" width="50%" @opened="open">
            <el-form ref="authorityEditForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-form-item label="权限名称" prop="userTypeName">
                    <el-input v-model="state.editForm.userTypeName"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="description">
                    <el-input v-model="state.editForm.description"></el-input>
                </el-form-item>
                <el-form-item label="菜单分配" prop="resource">
                    <el-tree :data="state.nodeList" show-checkbox default-expand-all node-key="id" ref="authorityTree"
                        highlight-current :props="state.defaultProps"></el-tree>
                </el-form-item>
                <div class="flex justify-between items-center">
                    <el-button type="primary" @click="updateRow">提交</el-button>
                    <el-button type="plain" @click="state.editAuthorityDialogVisible = false">返回</el-button>
                    <el-button @click="resetChecked">清空</el-button>
                </div>
            </el-form>
        </el-dialog>
        <el-row class="mb-1">
            <div class="w-full flex justify-end">
                <el-autocomplete v-model="state.stateData" @change="inputSearch" :fetch-suggestions="querySearchAsync"
                    placeholder="请输入关键字" @select="handleSelect" class="mr-2">
                    <template #suffix>
                        <el-icon color="#000">
                            <Search />
                        </el-icon>
                    </template>
                </el-autocomplete>
            </div>
        </el-row>
        <el-table :data="state.userTypeList" style="width: 100%" border>
            <el-table-column prop="UserTypeID" label="权限ID" width="80" align="center"></el-table-column>
            <el-table-column prop="UserTypeName" label="权限名" width="100" align="center"></el-table-column>
            <el-table-column label="资源">
                <template #default="scope">
                    <el-table :data="scope.row.Resources">
                        <el-table-column type="expand">
                            <template #default="props">
                                <el-table :data="props.row.SubMenuInfo" :border="true">
                                    <el-table-column label="子菜单ID" prop="ResourceID" align="center" />
                                    <el-table-column label="子菜单名" prop="ResourceName" align="center" />
                                    <el-table-column label="类型" prop="ResourceType" align="center" />
                                    <el-table-column label="图标" prop="Icon" align="center" />
                                    <el-table-column label="地址" prop="Path" align="center" />
                                </el-table>
                            </template>
                        </el-table-column>
                        <el-table-column prop="MainMenuID" label="主菜单ID" align="center"></el-table-column>
                        <el-table-column prop="MainMenuName" label="主菜单名" align="center"></el-table-column>
                        <el-table-column prop="MainMenuURL" label="地址" align="center"></el-table-column>
                        <el-table-column prop="MainMenuIcon" label="图标" align="center"></el-table-column>
                        <el-table-column prop="MainMenuOrder" label="排序" sortable align="center"></el-table-column>

                    </el-table>
                </template>
            </el-table-column>
            <el-table-column prop="Description" label="备注" width="100" align="center"></el-table-column>
            <el-table-column fixed="right" label="操作" width="150" align="center">
                <template #default="scope">
                    <el-button link type="warning" size="small" @click.prevent="openUpdata(scope.row)">
                        <el-icon>
                            <EditPen />
                        </el-icon>
                        编辑菜单
                    </el-button>
                    <el-button link type="danger" size="small" @click.prevent="deleteRow(scope.row.UserID)">
                        <el-icon>
                            <DeleteFilled />
                        </el-icon>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handlehSizeChange" @current-change="handlehCurrentChange" :page-sizes="[2, 3, 5]"
            :page-size="state.pageSize" layout="total, jumper, prev, pager, next, sizes" :total="state.total" class="mt-2">
        </el-pagination>
    </div>
</template>

<script setup>
import { ElTable } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { userTypeRead, userTypeCreate, userTypeUpDate, userTypeDelete, userTypeFindByName, findAllUserTypeName, findAllUserType } from "../api/usertype"
import { DeleteFilled, EditPen, Hide, ZoomIn, Delete, Plus, Search } from '@element-plus/icons-vue'

import { messageCreate } from "../api/message/message";
import { useTabsStore } from '../store/store'
const useData = useTabsStore()

const state = reactive({
    userTypeList: [],
    total: "",
    pageNum: 1,
    pageSize: 2,
    searchType: "exact",
    stateData: "",
    editAuthorityDialogVisible: false,
    nodeList: [],
    defaultProps: {
        children: 'children',
        label: 'label'
    },
    itemList: [],//节点回显值
    editForm: {
        userTypeID: '',
        userTypeName: '',
        description: '',
        resource: []
    },
    rules: {
        userTypeName: [
            { required: true, message: '请输入权限名', trigger: 'blur' },
        ],
        description: [
            { required: true, message: '请输入备注名', trigger: 'blur' },
        ],
        resource: [
            { required: true, message: '请选择节点', trigger: 'blur' },
        ]
    }
})
const authorityTree = ref()
const authorityEditForm = ref()
const init = async () =>
{
    const res = await userTypeRead({ pageSize: state.pageSize, pageNum: state.pageNum, userTypeName: state.stateData, searchType: state.searchType })
    state.userTypeList = res.data.UserTypeData
    console.log(state.userTypeList, "============>");
    state.total = res.data.total
    state.pageSize = res.data.pageSize
    state.pageNum = res.data.pageNum
}
// 分页
const handlehSizeChange = (val) =>
{
    state.pageSize = val;
    state.pageNum = 1;
    init()
}
const handlehCurrentChange = (val) =>
{
    state.pageNum = Math.ceil(val);
    init()
}
//  搜索查找
const inputSearch = () =>
{
    state.searchType = 'fuzzy' //执行模糊搜索
    console.log(state.stateData);
    init()
}
// 搜索
let timeout
// 触发过滤条件
const querySearchAsync = (queryString, cb) =>
{
    const results = queryString
        ? state.userTypeNames.filter(createFilter(queryString))
        : state.userTypeNames

    clearTimeout(timeout)
    timeout = setTimeout(() =>
    {
        cb(results)
    }, 3000 * Math.random())
}
// 创建过滤
const createFilter = (queryString) =>
{
    return (restaurant) =>
    {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
// 搜索框选择
const handleSelect = (item) =>
{
    state.stateData = item.value
    init()
    console.log(state.stateData, "搜索词")
}
// 获取所有的权限名
const getAllUserTypeName = async () =>
{
    const res = await findAllUserTypeName()
    console.log(res, "============>");
    state.userTypeNames = res.data
    state.userTypeNames = state.userTypeNames.map(function (item)
    {
        return { value: item.UserTypeName };
    });
}
// 获取选中元素节点
const getCheckedKeys = () =>
{
    const checkedKeys = authorityTree.value.getCheckedKeys();
    // 去除数组里面为undifined的元素
    checkedKeys.forEach(
        (item, index) =>
        {
            if (item === undefined) {
                checkedKeys.splice(index, 1);
            }
        })
    console.log("选中的子菜单ID:", checkedKeys);

    state.editForm.resource = checkedKeys
    // 转换成字符串 checkedKeys [0,2,5]转换成"[0,2,5]"
    state.editForm.resource = JSON.stringify(checkedKeys)
}
// 清空
const resetChecked = () =>
{
    authorityTree.value.setCheckedKeys([]);
}
// 提交
const updateRow = () =>
{
    getCheckedKeys()
    authorityEditForm.value.validate((valid) =>
    {
        console.log(state.editForm, "============>");
        if (valid) {
            userTypeUpDate(state.editForm).then(() =>
            {
                ElMessage.success("修改成功");
                messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 修改了权限列表数据`, operationType: 'edit' })
                state.editAuthorityDialogVisible = false;
                resetChecked();
                init();
            })
        }
    })
}
// 获取所有的菜单资源节点
const findAllUserTypeList = async () =>
{
    const res = await findAllUserType()
    state.nodeList = res.data
    state.nodeList = state.nodeList.map(mainMenu =>
    {
        return {
            label: mainMenu.mainMenuName,
            children: mainMenu.subMenus.map(subMenu =>
            {
                return {
                    id: subMenu.subMenuId,
                    label: subMenu.subMenuName,
                };
            }),
        };
    });
}
// 打开编辑窗口
const openUpdata = (row) =>
{
    console.log(row, "1115555");
    state.editForm.userTypeID = row.UserTypeID
    state.editForm.userTypeName = row.UserTypeName
    state.editForm.description = row.Description
    state.editAuthorityDialogVisible = true
    row.Resources.forEach(item =>
    {
        const items = item.SubMenuInfo.map(subMenu =>
        {
            return {
                id: subMenu.ResourceID,
                label: subMenu.ResourceName,
            };
        })
        state.itemList = [...state.itemList, ...items]
    })
}
// 窗口打开回调
const open = () =>
{
    authorityTree.value.setCheckedNodes(state.itemList)
}
onMounted(() =>
{
    init()
    getAllUserTypeName()
    findAllUserTypeList()
})
</script>


<style lang="scss" scoped></style>